"""
被多个线程竞争的资源称之为临界资源
临界资源通常需要锁进行保护
RLock ---> Reentrant Lock （重入锁）
current_thread() ---> 获得正在执行的当前线程
"""
import time
from concurrent.futures.thread import ThreadPoolExecutor

from threading import Thread, RLock, Condition, current_thread


class Account:

    def __init__(self):
        self.balance = 0
        self.lock = RLock()
        self.condition = Condition(self.lock)

    def deposit(self, money):
        with self.lock:
            new_balance = self.balance + money
            time.sleep(0.01)
            self.balance = new_balance
            # 唤醒等待中的线程
            self.condition.notify_all()

    def withdraw(self, money):
        with self.lock:
            while money > self.balance:
                # 让线程暂停释放掉获得的锁
                self.condition.wait()
            new_balance = self.balance - money
            time.sleep(0.01)
            self.balance = new_balance


def main():
    account = Account()
    pool = ThreadPoolExecutor(max_workers=16)
    # threads = []
    futures = []
    for _ in range(100):
        future = pool.submit(account.deposit, 1)
        futures.append(future)
        # t = Thread(target=account.deposit, args=(1, ))
        # threads.append(t)
        # t.start()
    for future in futures:
        future.result()
    # for t in threads:
    #     t.join()
    print(account.balance)


if __name__ == '__main__':
    main()
